<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/22
 * Time: 12:24
 */

namespace wechat\services;

use ttcommon\base\Data;
use wechat\models\WeConfig;
use yii\base\UserException;

class WeConfigService
{
    /**
     * 通过主键查询指定配置信息
     * @param integer $id we_config.id 主键
     * @param string|null $field 查询字段
     * @return string|array
     * @throws
     */
    public static function find($id, $field = null)
    {
        static $cache = [];
        if (!isset($cache[$id])) {
            if (!$row = WeConfig::find()->where(['id' => $id])->asArray()->one()) {
                throw new UserException('找不到指定微信配置:' . $id);
            }
            $cache[$id] = $row;
        }
        return $field ? Data::hasValue($cache[$id], $field) : $cache[$id];
    }

    /**
     * 查询应用类型
     * @param string $appid 应用的 id
     * @return mixed
     */
    public static function typeFromAppid($appid)
    {
        static $cache = [];
        if (!isset($cache[$appid])) {
            if (!$app = WeConfig::find()->where(['appid' => $appid])->select(['type'])->asArray()->one()) {
                $cache[$appid] = WeConfig::TYPE_UNKNOWN;
            } else {
                $cache[$appid] = $app['type'];
            }
        }
        return $cache[$appid];
    }
}